package com.ikingtech.framework.sdk.rpc.interceptor;

import com.ikingtech.framework.sdk.utils.Tools;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;

import static com.ikingtech.framework.sdk.context.constant.SecurityConstants.HEADER_CALLER;
import static com.ikingtech.framework.sdk.context.constant.SecurityConstants.HEADER_GATEWAY_REQUEST_ID;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class FeignClientInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header(HEADER_CALLER, "INNER");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == attributes) {
            //内部调用设置默认用户信息
            requestTemplate.header(HEADER_GATEWAY_REQUEST_ID, "DEFAULT_USER");
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        String requestId = request.getHeader(HEADER_GATEWAY_REQUEST_ID);
        if (Tools.Str.isBlank(requestId)) {
            //内部调用设置默认用户信息
            requestTemplate.header(HEADER_GATEWAY_REQUEST_ID, "DEFAULT_USER");
            return;
        }
        requestTemplate.header(HEADER_GATEWAY_REQUEST_ID, requestId);
    }
}
